package com.ebelter.scaleblesdk.ble.bluetooth.device;

import com.ebelter.scaleblesdk.ble.bluetooth.IBlueToothMessageCallBack;
import com.ebelter.scaleblesdk.util.ULog;

/**
 * 接收到的设备数据处理
 *
 * @author fenghui
 */
public abstract class AbstractDeviceDataHandle {
    //日志标签
    protected String TAG = "AbstractDeviceDataHandle";

    //设备类型
    protected int deviceType = -1;

    //ui数据回传
    protected IBlueToothMessageCallBack msgCallBack;

    //上一次接收数据时间(过滤重复数据的时候用)
    protected long lastReceiveDataMillis = 0;

    //上一次接收数据内容(过滤重复数据的时候用)
    protected String lastReceiveData = "";

    //设备mac地址
    private String deviceAddress = "";
    private byte[] deviceAddressBytes = new byte[6];

    //通讯数据是否加密
    private boolean isDataEncrypt = true;

    public AbstractDeviceDataHandle(IBlueToothMessageCallBack callback) {
        this.msgCallBack = callback;
    }

    /**
     * 处理数据
     *
     * @param data
     */
    public abstract void handlerData(byte[] data, String dataStr);

    /**
     * 检查是否接收重复消息（1、3秒内接收的消息；2、消息内容同缓存的内容一样）
     *
     * @param data
     * @return
     */
    protected boolean isTheSameData(String data) {
        if (System.currentTimeMillis() - lastReceiveDataMillis < 200
                && data.equals(lastReceiveData)) {
            lastReceiveDataMillis = System.currentTimeMillis();
            ULog.i(TAG, "接收到重复消息内容!");
            return true;
        }
        lastReceiveDataMillis = System.currentTimeMillis();
        lastReceiveData = data;
        return false;
    }

    /**
     * 下发消息到设备中
     *
     * @param bs
     */
    protected void sendDataToDevice(byte[] bs) {
        ULog.d(TAG, "send data to device, data is : " + bytestoString(bs));
        // send data to device, data is : -55,1,21
        this.msgCallBack.writeData(bs);
    }

    public IBlueToothMessageCallBack getMsgCallBack() {
        return msgCallBack;
    }

    //设置当前连接设备mac地址，用于下发数据加密使用
    public void setDeviceAddress(String mac) {
        this.deviceAddress = mac;
        if (mac != null && !mac.equals("")) {
            String[] deviceAddressArr = mac.split(":");
            for (int i = 0; i < deviceAddressArr.length; i++) {
                deviceAddressBytes[i] = (byte) Integer.parseInt(deviceAddressArr[i], 16);
            }
        }
    }

    public byte[] getDeviceAddressBytes() {
        return deviceAddressBytes;
    }

    public void setIsDataEncrypt(Boolean encrypt) {
        isDataEncrypt = encrypt;
    }

    public boolean isDataEncrypt() {
        return isDataEncrypt;
    }


    protected String bytestoString(byte[] bs) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bs) {
			sb.append(Integer.toHexString(b));
            sb.append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }
	public void sendDisconnectBt() {
		
	}
}